package org.aeon.fasttasks.core.manager;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author aeon
 * @createTime 2025/08/07  16:04
 * @description 用于管理多任务的整体完成情况 线程安全
 */
public class MultiStateLatch {

    /**
     * 单例，任何情况返回true
     */
    private static final MultiStateLatch EMPTY = new MultiStateLatch() {
        @Override
        public boolean getWhenStatusIsUnread() {
            return true;
        }

        @Override
        public MultiStateLatch add(AtomicBoolean status) {
            throw new UnsupportedOperationException("不支持添加成员");
        }

        @Override
        public boolean isEmpty() {
            return true;
        }
    };

    /**
     * 状态
     */
    private final Collection<AtomicBoolean> status;

    /**
     * 是否已读取
     */
    private volatile boolean read = false;

    private MultiStateLatch(AtomicBoolean... status) {
        this.status = new ArrayList<>();
        Collections.addAll(this.status, status);
    }

    /**
     * 单任务默认使用
     */
    public static MultiStateLatch of() {
        return EMPTY;
    }

    /**
     * 构造 MultiStateLatch
     */
    public static MultiStateLatch of(AtomicBoolean... status) {
        return new MultiStateLatch(status);
    }

    /**
     * 判断状态是否全部为true
     * 如果已读取过，则直接返回false
     *
     * @return
     */
    public synchronized boolean getWhenStatusIsUnread() {
        if (read) {
            return false;
        }
        synchronized (this) {
            if (read) {
                return false;
            }
            boolean match = true;
            for (AtomicBoolean atomicBoolean : status) {
                if (!atomicBoolean.get()) {
                    match = false;
                    break;
                }
            }
            if (match) {
                read = true;
            }
            return match;
        }
    }

    /**
     * 判断状态是否全部为true
     *
     * @return
     */
    public synchronized boolean getStatus() {
        for (AtomicBoolean atomicBoolean : status) {
            if (!atomicBoolean.get()) {
                return false;
            }
        }
        return true;
    }

    /**
     * 添加成员
     *
     * @return
     */
    public synchronized MultiStateLatch add(AtomicBoolean status) {
        this.status.add(status);
        reset();
        return this;
    }

    /**
     * 重置read标记
     */
    public void reset() {
        read = false;
    }

    /**
     * 判断是否为空
     *
     * @return
     */
    public boolean isEmpty() {
        return false;
    }
}
